package com.example.demo.utils;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 单例模式-懒汉式 并发不安全;synchronized 加锁解决，效率降低
 */
public class Singel2Utils {

    private static Singel2Utils singel1Utils;

    private Singel2Utils() {}

    /**
     * 第一种加锁 效率较低
     * @return
     */
    public static synchronized Singel2Utils getSingel22Utils() {
        if (singel1Utils == null) {
            singel1Utils = new Singel2Utils();
        }
        return singel1Utils;
    }
    /**
     * 第二种加锁 提高加锁后效率
     * 用volatile关键字修饰instance变量，使得instance在读、写操作前后都会插入内存屏障，避免重排序。
     * @return
     */
    private volatile static Singel2Utils singel2Utils;
    public static Singel2Utils getSingel2Utils() {
        if (singel2Utils == null) {
            synchronized (Singel2Utils.class) {
                if (singel2Utils == null)
                    singel2Utils = new Singel2Utils();
            }

        }
        return singel2Utils;
    }

    // https://www.cnblogs.com/dolphin0520/p/3920373.html
        public  AtomicInteger inc = new AtomicInteger();

        public  void increase() {
            inc.getAndIncrement();
        }

        public static void main(String[] args) {
            Singel2Utils utils = getSingel2Utils();
            for(int i=0;i<10;i++){
                new Thread(()->{
                    for(int j=0;j<1000;j++)
                        utils.increase();
                }).start();
            }
            while(Thread.activeCount()>1)  //保证前面的线程都执行完
                Thread.yield();
            System.out.println(utils.inc);
        }
}
